package com.cutJar.core;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;

import com.conf.log.LOG;
import com.conf.log.impl.LogImpl;
import com.cutJar.Exception.ResourceNullException;
import com.cutJar.util.CharStream;
import com.cutJar.util.Resource;

/**
 * <b>自定义加工class文本信息 需要子类impl完善</b>
 * <p>
 * 描述:<br>
 * 
 * @author 威 
 * <br>2018年3月31日 下午5:14:40 
 * @see com.cutJar.core.AbstractMachining
 * @since 1.0
 */
public class DefMachining extends AbstractMachining {
	/**
	 * 剪切预备开始
	 * @see com.cutJar.core.AbstractMachining#cutPreStart()
	 * @see #getTargetStream()
	 * @see #getTempStream()
	 * @see #doFor(BufferedReader, BufferedWriter, BufferedWriter)
	 */
	@Override
	public void cutPreStart() throws ResourceNullException {
		System.out.println("classTextPath :"+classTextPath);
		BufferedReader br = CharStream.getRead(Resource.getFileSystemResource(classTextPath));
		BufferedWriter bw = getTargetStream();
		BufferedWriter tempBw = getTempStream();
		try {
			doFor(br, bw, tempBw);
		} catch (IOException e) {
			LogImpl.getInstance().log(LOG.ERROR, e.getMessage());
		}finally{
			try{
				CharStream.free(br);
				CharStream.free(bw);
				CharStream.free(tempBw);
			}catch(IOException e){
				LogImpl.getInstance().log(LOG.ERROR, e.getMessage());}
		}
	}
	
	/**
	 * 循环对每一行进行操作
	 * <p>
	 * @param br
	 * @param bw
	 * @param tempBw
	 * @throws IOException
	 * void
	 * @see #mainStratege(BufferedWriter, BufferedWriter, String)
	 * @since 1.0
	 */
	private void doFor(BufferedReader br, BufferedWriter bw, BufferedWriter tempBw)
			throws IOException {
		String line;
		while((line = br.readLine()) != null){
			if(!line.trim().equals("")){
				allCount++;
				if(listener != null)
					listener.allPre();
				if(line.indexOf("[Opened") != 0)
					mainStratege(bw, tempBw, line);
			}
		}
	}
	
	/**
	 * 主要的处理方式
	 * <p>	 
	 * @param bw
	 * @param tempBw
	 * @param line
	 * @throws IOException
	 * void
	 * @since 1.0
	 */
	private void mainStratege(BufferedWriter bw, BufferedWriter tempBw, String line) throws IOException{
		if(line.indexOf(dectoryName+".jar") != -1){
			mainCount++;
			if(listener != null)
				listener.rtPre();
			bw.write(editLineData(line));
			bw.newLine();
		}else{
			tempBw.write(line);
			tempBw.newLine();
		}
	}

	@Override
	public void logResultInfo() {
		LogImpl.getInstance().log(LOG.ORDINARY, new StringBuilder("\r\n")
				.append("预备剪切结果: ")
				.append("\r\n")
				.append("			所有目标个数：")
				.append(allCount+"个")
				.append("\r\n")
				.append("			符合"+ this.dectoryName +"目标个数：")
				.append(mainCount+"个")
				.append("\r\n")
				.append("jre剪切预备完毕."));
	}
}
